package servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "login", value = "/login")
public class Demo4_LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        //1.获取页面的用户名和密码
        String username = request.getParameter("userName");
        String password = request.getParameter("password");

        //2.模拟验证用户名和密码是否正确
        if(username.equals("tiger") && password.equals("scott")){
            //3.1 servlet响应到页面的格式，设置为html
            response.setContentType("text/html;charset=utf-8");
            //3.2 获取字符输出流，作为响应返回的信息输出
            PrintWriter writer = response.getWriter();

            writer.print("<html>" +
                    "<head><title>登录结果</title></head>" +
                    "<body><p>登录成功</p></body>" +
                    "</html>");

            writer.close();
        }else{

            //3.3 响应的时候做页面重定向
            response.sendRedirect("/html/error.html");
        }

    }
}
